import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
// ShapeDrawerGUI

public class ShapeDrawer extends JFrame {
//

    private DrawArea drawArea = new DrawArea();
// ShapeDrawerGUI


    public ShapeDrawer() {
        this.setSize(400, 400); //


        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setTitle(" 图形绘制器 "); //

        this.add(drawArea, BorderLayout.CENTER);
//




        JComboBox<String> shapeSelector = new JComboBox<>(new String[]
                {" 正⽅形 ", "⻓⽅形 ", " 圆形 ", " 三⻆形 "});
//


        this.add(shapeSelector, BorderLayout.NORTH);
//


        shapeSelector.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JComboBox cb = (JComboBox) e.getSource();
                String shapeName = (String) cb.getSelectedItem();
                int size = 0; //初始化尺⼨变量

                boolean validInput = false; //标记⽤户输⼊是否有效

                while (!validInput) { //循环直到⽤户输⼊有效

                    String input = JOptionPane.showInputDialog(" 请输⼊" + shapeName + " 的尺⼨:");
                    try {
                        size = Integer.parseInt(input); //尝试将输⼊转换为整数

                                validInput = true; //如果成功转换，标记输⼊有效并退出循环

                    }
                    catch (NumberFormatException ex) {
                        JOptionPane.showMessageDialog(null, " 输⼊⽆效，请输⼊⼀个整 数。");
                        // 如果失败，提示⽤户重新输⼊

                    }
                }
                drawArea.setShape(shapeName, size); //更新图形和尺⼨

            }
        });
    }
//


        public static void main(String[] args) {
//





            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
//



                    new ShapeDrawer().setVisible(true);

                }
            });
        }
// DrawArea


    private static class DrawArea extends JPanel {
        private String shape = "正⽅形";
        private int size = 100; //添加尺⼨属性，默认为100
        public void setShape(String shape, int size) {
            this.shape = shape;
            this.size = size;
            this.repaint(); //请求重新绘制⾯板

        }
//其他代码⽆改变...



    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        switch (shape) {case " 正⽅形 ":
            g.drawRect(50, 50, size, size);
            break;
            case "⻓⽅形 ":
                g.drawRect(50, 50, size * 2, size);
                break;
            case " 圆形 ":
                g.drawOval(50, 50, size, size);
                break;
            case " 三⻆形 ":
                int[] xPoints = {50 + size / 2, 50, 50 + size};
                int[] yPoints = {50, 50 + size, 50 + size};
                g.drawPolygon(xPoints, yPoints, 3);
                break;
        }
            }
        }
    }